/**
 * 
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 *   
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * 
 */
package org.jiopi.ibean.bootstrap.util;

import java.io.File;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import org.jiopi.ibean.share.ShareUtil.IOUtil;

/**
 * 
 * 替换文件内容
 * 
 * @since 2010.4.18
 *
 */
public class FileContentReplacer {
	
	/**
	 * 将文件中的给定字符串替换为新的字符串
	 * @param from 源文件
	 * @param to   目标文件
	 * @param regex  
	 * @param replacement
	 * @throws IOException 
	 */
	public static void replaceAll(URL from,File to,String[] regex,String[]replacement) throws IOException{
		InputStream fis = null;
		InputStreamReader isr = null;
		BufferedReader br = null;
		
		FileOutputStream fos = null;
		OutputStreamWriter osw = null;
		BufferedWriter bw = null;
		try{
			fis = from.openStream();
			isr = new InputStreamReader(fis,"UTF-8");
			br = new BufferedReader(isr);
			
			fos = new FileOutputStream(to);
			osw = new OutputStreamWriter(fos,"UTF-8");
			bw = new BufferedWriter(osw);
			
			StringBuilder sb = new StringBuilder();
			String line = null;
			do{
				line = br.readLine();
				if(line!=null){
					sb.append(line).append("\n");
				}
			}while(line!=null);
			String replaceContent = sb.toString();
			for(int i=0;i<regex.length;i++){
				replaceContent = replaceContent.toString().replaceAll(regex[i], replacement[i]);
			}
			bw.write(replaceContent);
		}finally{
			IOUtil.close(br);
			IOUtil.close(isr);
			IOUtil.close(fis);
			
			IOUtil.close(bw);
			IOUtil.close(osw);
			IOUtil.close(fos);
		}
	}
}
